/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.gwt.apps.client.user;

import java.util.Date;
import java.util.List;

import net.bioteam.cloud.cluster.ActiveCluster;
import net.bioteam.cloud.cluster.ActiveHost;
import net.bioteam.cloud.cluster.ClusterStatus;
import net.bioteam.appweb.gwt.apps.client.StaticHolder;
import net.bioteam.appweb.gwt.apps.client.Util.ApplicationCallBack;
import net.bioteam.appweb.gwt.apps.client.Util.LinkLabel;
import net.bioteam.appweb.gwt.apps.client.Util.Util;
import net.bioteam.appweb.gwt.apps.clientandserver.ClusterInfo;
import net.bioteam.appweb.gwt.apps.clientandserver.Constant;
import net.bioteam.appweb.gwt.apps.clientandserver.ServerException;
import net.bioteam.appweb.gwt.apps.clientandserver.user.UserAction;
import net.bioteam.common.user.User;
import net.bioteam.common.user.UserInfo;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.DateDisplayFormat;
import com.smartgwt.client.types.FormErrorOrientation;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.HTMLPane;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.events.CloseClientEvent;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.PasswordItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.validator.CustomValidator;
import com.smartgwt.client.widgets.form.validator.LengthRangeValidator;
import com.smartgwt.client.widgets.form.validator.RegExpValidator;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.layout.VLayout;

public class AccountPanel extends HLayout
{

	private static ClusterDataSource cds;
	Canvas content;
	Canvas contentChild;
	Label emailLabel;
	Label viewEc2;
	Label deleteEc2;
	Label attachEc2;
	Label clusterInfo;
	Label subLink;
	Label clusterHistory;
	private static User user;

	public AccountPanel()
	{

		// setLayoutRightMargin(20);

		Canvas linkPanel = createLinkPanel();
		addMember(linkPanel);

		content = new Canvas();
		content.setHeight(500);
		content.setWidth(500);
		content.setMargin(20);
		// content.setBorder("5px solid green");

		addMember(content);
		cds=new ClusterDataSource();
	}

	private void setContent(Canvas can)
	{
		if (contentChild != null)
		{
			contentChild.destroy();
		}
		content.addChild(can);
		// content.redraw();
		contentChild = can;
	}

	private void changePassword()
	{
		VLayout layout = new VLayout();
		layout.setHeight100();
		layout.setWidth100();

		final Label infoLabel = new Label();
		infoLabel.setHeight(20);

		final DynamicForm form = new DynamicForm();
		// form.setBorder("2px solid red");
		form.setTitleWidth(250);
		form.setWidth(350);
		form.setCellBorder(5);

		form.setShowInlineErrors(true);
		form.setShowErrorText(true);
		form.setErrorOrientation(FormErrorOrientation.TOP);
		form.setRequiredTitleSuffix("<em style='color:red;'>***</em>");

		final PasswordItem pi = new PasswordItem("olpw");
		pi.setTitle("Original Password");
		pi.setWidth(100);
		pi.setRequired(true);

		LengthRangeValidator lrv = new LengthRangeValidator();
		lrv.setMin(new Integer(6));
		final PasswordItem p1 = new PasswordItem("p1");
		p1.setTitle("new Password");
		p1.setWidth(100);
		p1.setRequired(true);
		p1.setValidators(lrv);

		LengthRangeValidator lrv1 = new LengthRangeValidator();
		lrv1.setMin(new Integer(6));

		CustomValidator matchValidator = new CustomValidator()
		{

			@Override
			protected boolean condition(Object value)
			{
				if (value == null)
				{
					setErrorMessage("Required");
					return false;
				}
				if (p1.getValue() == null)
				{
					return false;
				}
				if (!value.toString().equals(p1.getValue().toString()))
				{
					setErrorMessage("new password does not match");
					return false;
				}
				return true;
			}
		};

		final PasswordItem p2 = new PasswordItem("p2");
		p2.setTitle("new Password again");
		p2.setWidth(100);
		p2.setRequired(true);
		p2.setValidators(lrv1, matchValidator);

		form.setItems(pi, p1, p2);

		layout.addMember(form);

		LayoutSpacer spacer1 = new LayoutSpacer();
		spacer1.setHeight(20);
		layout.addMember(spacer1);

		infoLabel.setVisible(false);
		infoLabel.setAnimateShowTime(1200);
		infoLabel.setWidth(200);
		infoLabel.setStyleName("red");
		infoLabel.setLayoutAlign(Alignment.CENTER);
		layout.addMember(infoLabel);

		IButton button = new IButton("Change");
		button.setLayoutAlign(Alignment.CENTER);
		layout.addMember(button);

		button.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				if (!form.validate())
					return;
				ApplicationCallBack<User> callback = new ApplicationCallBack<User>()
				{
					public void onFailureAfter(Throwable caught)
					{
						SC.warn(caught.getMessage(), StaticHolder.dumpB);
					}

					public void onSuccessAfter(User result)
					{
						user = result;
						StaticHolder.setMessage(infoLabel, "Password is updated", 5);
					}

					public void execute()
					{
						UserAction.Util.getInstance().changePassword(pi.getValue().toString(), p1.getValue().toString(), this);
					}

				};
				callback.execute();

			}
		});

		setContent(layout);

	}

	private void attachEC2()
	{
		VLayout layout = new VLayout();
		layout.setHeight100();
		layout.setWidth100();

		final Label infoLabel = new Label();
		infoLabel.setHeight(60);

		final DynamicForm form = new DynamicForm();
		// form.setBorder("2px solid red");
		form.setTitleWidth(250);
		form.setWidth(350);
		form.setCellBorder(5);

		form.setShowInlineErrors(true);
		form.setShowErrorText(true);
		form.setErrorOrientation(FormErrorOrientation.TOP);
		form.setRequiredTitleSuffix("<em style='color:red;'>***</em>");

		final TextItem ec2Userid = new TextItem("ec2userid");
		ec2Userid.setTitle("EC2 user id");
		ec2Userid.setWidth(100);
		ec2Userid.setRequired(true);

		final TextItem accessKey = new TextItem("accesskey");
		accessKey.setTitle("AWS Access Key");
		accessKey.setWidth(100);
		accessKey.setRequired(true);

		final TextItem secretKey = new TextItem("secretKey");
		secretKey.setTitle("AWS secret key");
		secretKey.setWidth(100);
		secretKey.setRequired(true);

		form.setItems(ec2Userid, accessKey, secretKey);

		layout.addMember(form);

		LayoutSpacer spacer1 = new LayoutSpacer();
		spacer1.setHeight(20);
		layout.addMember(spacer1);

		infoLabel.setVisible(false);
		infoLabel.setAnimateShowTime(1200);
		infoLabel.setWidth(200);
		infoLabel.setStyleName("red");
		infoLabel.setLayoutAlign(Alignment.CENTER);
		infoLabel.setWrap(true);
		layout.addMember(infoLabel);

		IButton button = new IButton("Attach");
		button.setLayoutAlign(Alignment.CENTER);
		//layout.addMember(button);
		
		

		button.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				if (!form.validate())
					return;
				ApplicationCallBack<User> callback = new ApplicationCallBack<User>()
				{
					public void onFailureAfter(Throwable caught)
					{
						SC.warn(caught.getMessage(), StaticHolder.dumpB);
					}

					public void onSuccessAfter(User result)
					{
						user = result;
						viewEc2.show();
						deleteEc2.show();
						attachEc2.hide();
						clusterInfo.show();
						subLink.show();
						StaticHolder.setMessage(infoLabel, "EC2 access information is attached. Please subscribe cloud service. It is required to run application in dedicated computing cloud.", 10);
						
					}

					public void execute()
					{
						UserInfo info = new UserInfo();
						info.setEc2Userid(ec2Userid.getValue().toString());
						info.setAccessKey(accessKey.getValue().toString());
						info.setSecretKey(secretKey.getValue().toString());
						UserAction.Util.getInstance().attachEC2Info(info, this);
					}

				};
				callback.execute();

			}
		});

		
		HLayout h=new HLayout();
		LinkLabel subLabel=new LinkLabel("subscribe cloud service");
		subLabel.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				Util.open("https://aws-portal.amazon.com/gp/aws/user/subscription/index.html?ie=UTF8&offeringCode=311CB106");
			}
		});
		subLabel.setWidth(150);
		//subLabel.setBackgroundColor("green");
		h.addMember(button);
		h.addMember(subLabel);
		h.setWidth(300);
		h.setLayoutAlign(Alignment.CENTER);
		//h.setBackgroundColor("blue");
		h.setHeight(30);
		layout.addMember(h);
		setContent(layout);
		

	}

	private void changeEmail()
	{
		VLayout layout = new VLayout();
		layout.setHeight100();
		layout.setWidth100();

		final Label infoLabel = new Label();
		infoLabel.setHeight(20);

		final DynamicForm form = new DynamicForm();
		// form.setBorder("2px solid red");
		form.setTitleWidth(250);
		form.setWidth(350);
		// form.setCellBorder(5);

		form.setShowInlineErrors(true);
		form.setShowErrorText(true);
		form.setErrorOrientation(FormErrorOrientation.TOP);
		form.setRequiredTitleSuffix("<em style='color:red;'>***</em>");

		final TextItem email = new TextItem("email");
		email.setTitle("new email");
		email.setWidth(100);
		email.setRequired(true);
		RegExpValidator regV = new RegExpValidator();
		regV.setExpression(".+@.+");
		regV.setErrorMessage("invalid email address");
		email.setValidators(regV);

		form.setItems(email);

		layout.addMember(form);

		LayoutSpacer spacer1 = new LayoutSpacer();
		spacer1.setHeight(20);
		layout.addMember(spacer1);

		infoLabel.setVisible(false);
		infoLabel.setAnimateShowTime(1200);
		infoLabel.setWidth(200);
		infoLabel.setStyleName("red");
		infoLabel.setLayoutAlign(Alignment.CENTER);
		layout.addMember(infoLabel);

		IButton button = new IButton("Change");
		button.setLayoutAlign(Alignment.CENTER);
		layout.addMember(button);

		button.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				if (!form.validate())
					return;
				ApplicationCallBack<User> callback = new ApplicationCallBack<User>()
				{
					public void onFailureAfter(Throwable caught)
					{
						SC.warn(caught.getMessage(), StaticHolder.dumpB);
					}

					public void onSuccessAfter(User result)
					{
						user = result;
						emailLabel.setContents(user.getEmail());
						StaticHolder.setMessage(infoLabel, "Email is updated", 5);
					}

					public void execute()
					{
						UserAction.Util.getInstance().changeEmail(email.getValue().toString(), this);
					}

				};
				callback.execute();

			}
		});

		setContent(layout);

	}

	private void showEc2Info()
	{
		ListGrid grid = new ListGrid();
		grid.setWidth(400);
		grid.setHeight(100);
		grid.setAlternateRecordStyles(true);
		grid.setShowAllRecords(true);
		grid.setShowHeader(false);

		ListGridRecord[] records = new ListGridRecord[3];
		ListGridRecord record = new ListGridRecord();
		record.setAttribute("name", "EC2 User ID");
		record.setAttribute("value", user.getUserInfo().getEc2Userid());
		records[0] = record;

		record = new ListGridRecord();
		record.setAttribute("name", "Access Key");
		record.setAttribute("value", user.getUserInfo().getAccessKey());
		records[1] = record;

		record = new ListGridRecord();
		record.setAttribute("name", "Secret Key");
		record.setAttribute("value", user.getUserInfo().getSecretKey());
		records[2] = record;

		ListGridField nameField = new ListGridField("name", 100);
		ListGridField valueField = new ListGridField("value", 300);
		grid.setFields(nameField, valueField);
		grid.setData(records);

		setContent(grid);

	}

	public Canvas createLinkPanel()
	{
		VLayout layout = new VLayout();
		layout.setHeight(300);
		layout.setWidth(200);
		layout.setMargin(20);
		layout.setBorder("1px solid gray");
		//layout.setShowEdges(true);

		LayoutSpacer spacer = new LayoutSpacer();
		spacer.setHeight(50);
		layout.addMember(spacer);

		emailLabel = new Label(user.getEmail());
		emailLabel.setHeight(20);
		layout.addMember(emailLabel);

		Label pw = new LinkLabel("Change Password");
		pw.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				changePassword();

			}
		});
		layout.addMember(pw);

		Label email = new LinkLabel("Change email");
		email.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				changeEmail();

			}
		});
		layout.addMember(email);

		viewEc2 = new LinkLabel("View EC2 credential");
		if (user.getUserInfo() == null || user.getUserInfo().getEc2Userid() == null)
			viewEc2.setVisible(false);
		viewEc2.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				showEc2Info();
			}
		});
		layout.addMember(viewEc2);

		deleteEc2 = new LinkLabel("delete EC2 credential");
		if (user.getUserInfo() == null || user.getUserInfo().getEc2Userid() == null)
			deleteEc2.setVisible(false);
		deleteEc2.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{

				final ApplicationCallBack<String> callback = new ApplicationCallBack<String>()
				{

					public void onFailureAfter(Throwable caught)
					{
						SC.warn(caught.getMessage(), StaticHolder.dumpB);
					}

					public void onSuccessAfter(String result)
					{
						viewEc2.hide();
						deleteEc2.hide();
						attachEc2.show();
						clusterInfo.hide();
						subLink.hide();
						SC.say("EC2 credential is deleted", StaticHolder.dumpB);
					}

					public void execute()
					{
						UserAction.Util.getInstance().deleteEc2Info(this);
					}

				};


				SC.confirm(" Delete EC2 identity ?", new BooleanCallback()
				{

					public void execute(Boolean value)
					{
						if (value != null && value)
						{
							callback.execute();
						}
					}

				});
				
			}
		});
		layout.addMember(deleteEc2);

		attachEc2 = new LinkLabel("attach EC2 credential");
		if (user.getUserInfo() != null && user.getUserInfo().getEc2Userid() != null)
			attachEc2.setVisible(false);
		attachEc2.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				attachEC2();

			}
		});
		layout.addMember(attachEc2);

		clusterInfo = new LinkLabel("view Running cluster");
		if (!user.hasECCredential())
			clusterInfo.setVisible(false);
		clusterInfo.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				loadCluster();
			}
		});
		layout.addMember(clusterInfo);
		
		
		clusterHistory = new LinkLabel("view cluster history");
		clusterHistory.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				showClusterHistory();
			}
		});
		layout.addMember(clusterHistory);
		
		
		subLink = new LinkLabel("subscribe cloud service");
		if (!user.hasECCredential())
			subLink.setVisible(false);
		subLink.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				Util.open("https://aws-portal.amazon.com/gp/aws/user/subscription/index.html?ie=UTF8&offeringCode=311CB106");
			}
		});
		layout.addMember(subLink);
		

		return layout;
	}

	private static void loadCluster()
	{
		ApplicationCallBack<ActiveCluster[]> callback = new ApplicationCallBack<ActiveCluster[]>()
		{

			public void onFailureAfter(Throwable caught)
			{
				if (caught instanceof ServerException)
				{
					ServerException se = (ServerException) caught;
					if (se.getCode() == ServerException.NO_EC)
					{
						SC.warn("You do not have EC2 Credential. Please attach EC2 credential to you acocunt first", StaticHolder.dumpB);
						return;
					}
				}
				SC.warn(caught.getMessage(), StaticHolder.dumpB);
			}

			public void onSuccessAfter(ActiveCluster[] acs)
			{
				StaticHolder.accountPanel.showCluster(acs);
			}

			public void execute()
			{
				UserAction.Util.getInstance().getActiveCluster(true, this);
			}

		};
		callback.execute();

	}
	private void updateGridData(ListGrid cGrid, ActiveCluster[] acs)
	{
		ListGridRecord rs[] = new ListGridRecord[acs.length];
		for (int i = 0; i < acs.length; i++)
		{
			ActiveCluster ac = acs[i];
			ListGridRecord r = new ListGridRecord();
			r.setAttribute("id", ac.getId());
			r.setAttribute("requestTime", ac.getRequestTime());
			if (ac.getHosts() == null || ac.getHosts().isEmpty())
			{
				r.setAttribute("expire", "NA");
			} else
			{
				int elapsed = (int) (new Date().getTime() - ac.getHead().getStarttime().getTime()) / 60000;
				int duration = ac.getDurationhour() * 60;
				int remaining = duration - elapsed;
				r.setAttribute("expire", remaining);
			}
			r.setAttribute("status", ac.getStatus().toString());
			r.setAttribute("cluster", ac);
			r.setAttribute("hosts", "computer");
			r.setAttribute("web", "web");
			r.setAttribute("key", "keys");
			r.setAttribute("note", ac.getNote());
			rs[i] = r;
		}
		cGrid.setData(rs);
	}
	
	public void showCluster(ActiveCluster[] acs)
	{
		SectionStack ss=new SectionStack();
		ss.setWidth(695);
		ss.setHeight100();

		final ListGrid cGrid = new ListGrid();
		cGrid.setWidth(695);
		cGrid.setHeight100();
		cGrid.setOverflow(Overflow.CLIP_H);
		
		ImgButton refresh = new ImgButton();
		refresh.setSrc("[SKIN]actions/refresh.png");
		refresh.setSize(16);
		refresh.setShowFocused(false);
		refresh.setShowRollOver(false);
		refresh.setShowDown(false);
		refresh.setPrompt("reload");
		refresh.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				StaticHolder.setStatusMessage("reload active cluster", 3);
				ApplicationCallBack<ActiveCluster[]> callback = new ApplicationCallBack<ActiveCluster[]>()
				{

					public void onFailureAfter(Throwable caught)
					{
						if (caught instanceof ServerException)
						{
							ServerException se = (ServerException) caught;
							if (se.getCode() == ServerException.NO_EC)
							{
								SC.warn("You do not have EC2 Credential. Please attach EC2 credential to you acocunt first", StaticHolder.dumpB);
								return;
							}
						}
						SC.warn(caught.getMessage(), StaticHolder.dumpB);
					}

					public void onSuccessAfter(ActiveCluster[] acs)
					{
						updateGridData(cGrid, acs);
					}

					public void execute()
					{
						UserAction.Util.getInstance().getActiveCluster(true, this);
					}

				};
				callback.execute();

			}
		});


		cGrid.setDateFormatter(DateDisplayFormat.TOUSSHORTDATETIME);
		cGrid.setEmptyMessage("No running cluster");
		cGrid.setAlternateRecordStyles(true);
		cGrid.setShowAllRecords(true);
		cGrid.setShowEmptyMessage(true);
		cGrid.setWrapCells(true);
		cGrid.setCellHeight(50);

		ListGridField idField = new ListGridField("id", "ID", 60);
		idField.setType(ListGridFieldType.INTEGER);

		ListGridField requestTimeField = new ListGridField("requestTime", "Request Time", 100);
		requestTimeField.setType(ListGridFieldType.DATE);
		requestTimeField.setDateFormatter(DateDisplayFormat.TOUSSHORTDATETIME);

		ListGridField statusField = new ListGridField("status", "Status", 100);
		statusField.setType(ListGridFieldType.TEXT);
		statusField.setCellFormatter(new CellFormatter()
		{

			public String format(Object value, ListGridRecord record, int rowNum, int colNum)
			{
				if (value.toString().equals(ClusterStatus.BEFORESTART.toString()))
				{
					return "PENDING";
				} else if (value.toString().equals(ClusterStatus.PRESTART.toString()))
				{
					return "CONFIGURING";
				} else if (value.toString().equals(ClusterStatus.BEFORESTART))
				{
					return "STARTING";
				}
				return value.toString();
			}
		});

		ListGridField expireField = new ListGridField("expire", "Mins to Expires", 110);
		expireField.setType(ListGridFieldType.INTEGER);

		ListGridField hosts = new ListGridField("hosts", "", 40);
		hosts.setType(ListGridFieldType.IMAGE);
		hosts.setImageURLSuffix(".png");

		 ListGridField web = new ListGridField("web", "", 40);
		 web.setType(ListGridFieldType.IMAGE);
		 web.setImageURLSuffix(".png");
		
		 ListGridField key = new ListGridField("key", "", 40);
		 key.setType(ListGridFieldType.IMAGE);
		 key.setImageURLSuffix(".png");

		ListGridField note = new ListGridField("note", "Note", 200);
		note.setType(ListGridFieldType.TEXT);

		cGrid.setFields(idField, requestTimeField, statusField, expireField, hosts, web, key, note);
		//cGrid.setFields(idField, requestTimeField, statusField, expireField, hosts, note);
		updateGridData(cGrid, acs);

		cGrid.addCellClickHandler(new CellClickHandler()
		{

			public void onCellClick(CellClickEvent event)
			{
				ListGridRecord record = event.getRecord();
				int colNum = event.getColNum();
				if (colNum == 4)
				{
					ActiveCluster ac = (ActiveCluster) record.getAttributeAsObject("cluster");
					showHostsGrid(ac.getHosts());
				} 
				else if (colNum == 5)
				{
					ActiveCluster ac = (ActiveCluster) record.getAttributeAsObject("cluster");
					Util.open("http://" + ac.getHead().getExternalName() + ":8080/" + Constant.APPWEB_CONTEXT);
				} else if (colNum == 6)
				{
					ActiveCluster ac = (ActiveCluster) record.getAttributeAsObject("cluster");
					String href="/"+Constant.APPWEB_CONTEXT+"/apps/user/content/cluster/key/"+ac.getId();
					Util.open(href);
					//showKey(ac.getId());
				}
			}
		});
		
		SectionStackSection section1 = new SectionStackSection();
		section1.setTitle("active cluster");
		section1.setItems(cGrid);
		section1.setControls(refresh);
		section1.setExpanded(true);
		section1.setCanCollapse(false);

		ss.setSections(section1);
		ss.setAnimateSections(false);
		setContent(ss);
	}

	public void showKey(final long id)
	{
		ApplicationCallBack<String> callback = new ApplicationCallBack<String>()
		{

			public void onFailureAfter(Throwable caught)
			{
				SC.warn(caught.getMessage(), StaticHolder.dumpB);
			}

			public void onSuccessAfter(String result)
			{
				String htmlRet = result.replaceAll("\n", "</br>");
				final Window win = new Window();
				win.setWidth(600);
				win.setHeight(350);
				win.setTitle("Cluster key");
				win.setShowMinimizeButton(false);
				win.setIsModal(true);
				win.centerInPage();
				// win.setAutoSize(true);
				win.setShowCloseButton(true);
				win.addCloseClickHandler(new CloseClickHandler()
				{

					public void onCloseClick(CloseClientEvent event)
					{
						// win.hide();
						win.destroy();
					}
				});
				HTMLPane panel = new HTMLPane();
				panel.setContents(htmlRet);
				panel.setOverflow(Overflow.AUTO);
				panel.setHeight100();
				panel.setWidth100();
				win.addItem(panel);
				win.show();
			}

			public void execute()
			{
				UserAction.Util.getInstance().getClusterKey(id, this);
			}

		};
		callback.execute();

	}

	public void showHostsGrid(List<ActiveHost> hosts)
	{
		final Window win = new Window();
		win.setWidth(650);
		win.setHeight(400);
		win.setTitle("Hosts");
		win.setShowMinimizeButton(false);
		win.setIsModal(true);
		win.centerInPage();
		win.setAutoSize(true);
		win.setShowCloseButton(true);
		win.addCloseClickHandler(new CloseClickHandler()
		{

			public void onCloseClick(CloseClientEvent event)
			{
				// win.hide();
				win.destroy();
			}
		});

		ListGrid jGrid = new ListGrid();
		jGrid.setDateFormatter(DateDisplayFormat.TOUSSHORTDATETIME);
		// jGrid.setEmptyMessage("No hosts");
		jGrid.setAlternateRecordStyles(true);
		jGrid.setShowAllRecords(true);
		jGrid.setWidth(650);
		jGrid.setHeight(400);
		// jGrid.setShowEmptyMessage(true);

		ListGridField idField = new ListGridField("id", "ID");
		idField.setHidden(true);

		ListGridField instanceIDField = new ListGridField("instance", "Instance ID", 100);
		ListGridField headField = new ListGridField("head", "Head?", 40);
		headField.setCellFormatter(new CellFormatter()
		{

			public String format(Object value, ListGridRecord record, int rowNum, int colNum)
			{
				if ((Boolean) value)
				{
					return "Y";
				} else
				{
					return "N";
				}
			}
		});
		ListGridField startTime = new ListGridField("start", "Start Time", 100);
		startTime.setType(ListGridFieldType.DATE);
		ListGridField shutTime = new ListGridField("shut", "Halt Time", 100);
		shutTime.setType(ListGridFieldType.DATE);

		ListGridField dnsName = new ListGridField("dns", "External DNS Name", 300);
		jGrid.setFields(idField, instanceIDField, headField, startTime, shutTime, dnsName);
		ListGridRecord rs[] = new ListGridRecord[hosts.size()];
		int i = 0;
		for (ActiveHost host : hosts)
		{
			ListGridRecord r = new ListGridRecord();
			r.setAttribute("id", host.getId());
			r.setAttribute("instance", host.getInstanceid());
			r.setAttribute("head", host.isHead());
			r.setAttribute("start", host.getStarttime());
			r.setAttribute("shut", host.getShutTime());
			r.setAttribute("dns", host.getExternalName());
			rs[i++] = r;
		}
		jGrid.setData(rs);

		win.addItem(jGrid);
		win.show();
	}

	public static void showAccount(final String link)
	{
		if (StaticHolder.accountPanel != null)
		{
			com.google.gwt.user.client.Window.setTitle("Account Profile");
			StaticHolder.content.switchPanel(StaticHolder.accountPanel);
		}
		ApplicationCallBack<User> callback = new ApplicationCallBack<User>()
		{

			public void onFailureAfter(Throwable caught)
			{
				SC.warn(caught.getMessage(), StaticHolder.dumpB);
			}

			public void onSuccessAfter(User result)
			{
				AccountPanel.user = result;
				StaticHolder.accountPanel = new AccountPanel();
				com.google.gwt.user.client.Window.setTitle("Account Profile");
				StaticHolder.content.addChild(StaticHolder.accountPanel);
				StaticHolder.content.switchPanel(StaticHolder.accountPanel);
				if (link != null)
				{
					if (link.equals("cluster"))
						loadCluster();
				}
			}

			public void execute()
			{
				UserAction.Util.getInstance().getAccount(this);
			}

		};
		callback.execute();

	}
	public void showClusterHistory()
	{
		SectionStack ss=new SectionStack();
		ss.setWidth(655);
		ss.setHeight100();

		final ListGrid cGrid = new ListGrid();
		cGrid.setWidth(655);
		cGrid.setHeight100();
		cGrid.setOverflow(Overflow.CLIP_H);
		
		ImgButton refresh = new ImgButton();
		refresh.setSrc("[SKIN]actions/refresh.png");
		refresh.setSize(16);
		refresh.setShowFocused(false);
		refresh.setShowRollOver(false);
		refresh.setShowDown(false);
		refresh.setPrompt("reload");
		refresh.addClickHandler(new ClickHandler()
		{

			public void onClick(ClickEvent event)
			{
				StaticHolder.setStatusMessage("reload cluster history...", 3);
				cGrid.invalidateCache();
				cGrid.fetchData();
			}
		});


		cGrid.setDateFormatter(DateDisplayFormat.TOUSSHORTDATETIME);
		cGrid.setEmptyMessage("No cluster");
		cGrid.setAlternateRecordStyles(true);
		cGrid.setShowAllRecords(false);
		cGrid.setCanSort(false);
		cGrid.setShowEmptyMessage(true);
		cGrid.setWrapCells(true);
		cGrid.setCellHeight(40);

		ListGridField idField = new ListGridField("id", "ID", 60);
		idField.setType(ListGridFieldType.INTEGER);

		ListGridField requestTimeField = new ListGridField("requestTime", "Request Time", 100);
		requestTimeField.setType(ListGridFieldType.DATE);
		requestTimeField.setDateFormatter(DateDisplayFormat.TOUSSHORTDATETIME);

		ListGridField statusField = new ListGridField("status", "Status", 100);
		statusField.setType(ListGridFieldType.TEXT);
		statusField.setCellFormatter(new CellFormatter()
		{

			public String format(Object value, ListGridRecord record, int rowNum, int colNum)
			{
				if (value.toString().equals(ClusterStatus.BEFORESTART.toString()))
				{
					return "PENDING";
				} else if (value.toString().equals(ClusterStatus.PRESTART.toString()))
				{
					return "CONFIGURING";
				} else if (value.toString().equals(ClusterStatus.BEFORESTART))
				{
					return "STARTING";
				}
				return value.toString();
			}
		});

		
		ListGridField elapsed = new ListGridField("elapsed", "Elapsed Hours", 80);
		elapsed.setType(ListGridFieldType.INTEGER);
		
		ListGridField hosts = new ListGridField("hosts", "Hosts", 40);
		hosts.setType(ListGridFieldType.INTEGER);


		ListGridField note = new ListGridField("note", "Note", 255);
		note.setType(ListGridFieldType.TEXT);


		cGrid.setFields(idField, requestTimeField, statusField, elapsed, hosts, note);
		cGrid.setDataSource(cds);
		cGrid.setDataPageSize(20);
		cGrid.setDrawAheadRatio(1.5f);

		
		SectionStackSection section1 = new SectionStackSection();
		section1.setTitle("cluster history");
		section1.setItems(cGrid);
		section1.setControls(refresh);
		section1.setExpanded(true);
		section1.setCanCollapse(false);

		ss.setSections(section1);
		ss.setAnimateSections(false);
		setContent(ss);
		cGrid.fetchData();
	}
}
